import { router, addRoutes } from '@/router'
import { getToken } from '@/composables/auth'
import { hideFullLoading, showFullLoading, toast } from '@/composables/util'
import { useUserStore } from '@/stores'
let hasGetInfo = false
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // console.log(to)

  showFullLoading()
  const token = getToken()
  // 没有登陆，强制跳转回登录页
  if (!token && to.path !== '/login') {
    toast('请先登录', 'error')
    return next({ path: '/login' })
  }
  // 防止重复登录
  if (token && to.path === '/login') {
    toast('请勿重复登录', 'error')
    return next({ path: from.path ? from.path : '/' })
  }
  // 如果用户登陆了，自动获取用户信息，存储在pinia中
  let hasNewRoutes = false
  if (token && !hasGetInfo) {
    const userStore = useUserStore()
    await userStore.getInfo()
    // console.log(res)
    hasGetInfo = true
    hasNewRoutes = addRoutes(userStore.menusList)
  }
  // 设置页面标题
  // console.log(to)
  let title = (to.meta.title ? to.meta.title : '') + '-商城后台'
  document.title = title
  // next()
  hasNewRoutes ? next(to.fullPath) : next()
})

// 全局后置守卫
router.afterEach((to, from) => hideFullLoading())
